package com.lixiang.userinfo.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 全局过滤器(处理权限登录问题)
 * @author 李湘
 * @date 2018-10-21
 */
@Controller
public class GlobalInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession(false);
		//ServletOutputStream out = response.getOutputStream();
		//printWriter和@responseBody注解冲突 改用 outputstream
		//json封装的对象
		ObjectMapper mapper = new ObjectMapper();
		if(session!=null){
			//判断是否登陆
			if("yes".equals(session.getAttribute("isLogin"))){
				//判断用户是否为普通销售
				if((int)session.getAttribute("authLevel")==1){	
					//判断权限
					String str = request.getRequestURI();
					/*int index = str.lastIndexOf("/");
					int index2 = str.lastIndexOf(".");
					str =  str.substring(index, index2);
					str = str.substring(0,5);*/  
					if(str.indexOf("/user/save") != -1){
						System.out.println("匹配");
						return true;
					}else{
						System.out.println("不匹配");
						ApiResult result = ApiResult.failure(ResultCode.PERMISSION_NO_ACCESS);
						//将对象转换成json格式字符串
				        String mapJackson = mapper.writeValueAsString(result);
						//out.print(mapJackson);
				        PrintWriter pw = response.getWriter();
				        pw.write(mapJackson);
				        //关闭printwriter
				        pw.close();
						return false;
					}
				}
				return true;
			}else{
				return false;
			}
		}else{
			ApiResult result = ApiResult.failure(ResultCode.USER_NOT_LOGGED_IN);
			String mapJackson = mapper.writeValueAsString(result);
			PrintWriter pw = response.getWriter();
			pw.write(mapJackson);
			pw.close();
			return false;
		}
	}
	
}